﻿using MediatR;
using Newtonsoft.Json;
using Warehouse.Domain;
using Warehouse.Domain.DTO;
using Warehouse.Infrstructre.Imp;
using Warehouse.Infrstructre.Interface;
using Warehouse.Read.API.Applcation.Command.MovelibraryCommand;
using static WMSpublic.ParseAPI;
using WMSpublic;
using System.Diagnostics.Contracts;
using Microsoft.AspNetCore.Server.IISIntegration;
using static Warehouse.Read.API.Applcation.CommandHandlers.EnterStoragesCommandHandler.EnterStoragesSelectCommandHandler;

namespace Warehouse.Read.API.Applcation.CommandHandlers.MovelibraryCommandHandlers
{
    public class SelectMovelibraryCommandHandlers : IRequestHandler<SelectMovelibraryCommand, PageDTO<MovelibraryMoveProductDTO>>
    {
        private readonly IMovelibraryRepository _movelibraryRep;
        private readonly IMoveProductRepository _moveProductRep;
        private readonly IEnterStoragesRepsitory _enterStoragesRep;
        private readonly IEnterStoragesInfoRepsitory _enterStoragesInfoRep;
        private readonly IWarehouseRepository _warehouseRep;
        private readonly IStorehouseRepository _storehouseRep;

        public SelectMovelibraryCommandHandlers(IMovelibraryRepository movelibraryRep, IMoveProductRepository moveProductRep, IEnterStoragesRepsitory enterStoragesRep, IEnterStoragesInfoRepsitory enterStoragesInfoRep, IWarehouseRepository warehouseRep, IStorehouseRepository storehouseRep)
        {
            _movelibraryRep = movelibraryRep;
            _moveProductRep = moveProductRep;
            _enterStoragesRep = enterStoragesRep;
            _enterStoragesInfoRep = enterStoragesInfoRep;
            _warehouseRep = warehouseRep;
            _storehouseRep = storehouseRep;
        }

        public async Task<PageDTO<MovelibraryMoveProductDTO>> Handle(SelectMovelibraryCommand request, CancellationToken cancellationToken)
        {
            List<Products> products = await GetProductsList(1, 1000);
            PageDTO<MovelibraryMoveProductDTO> page = new PageDTO<MovelibraryMoveProductDTO>();
            var list = from a in await _movelibraryRep.GetAllAsyns()
                       join b in await _moveProductRep.GetAllAsyns()
                       on a.MovelibraryCode equals b.MovelibraryCode
                       where a.office_id == request.office_id && a.IsDel == false
                       //join c in await _enterStoragesInfoRep.GetAllAsyns()
                       //on b.ProductsID equals c.ProductsID
                       join g in products on b.ProductsID equals g.ProductsID
                       //join f in await _enterStoragesRep.GetAllAsyns()
                       //on c.StockId equals f.StockId
                       join e in await _storehouseRep.GetAllAsyns() on b.Movelocation equals e.StorehouseId
                       join d in await _warehouseRep.GetAllAsyns() on e.WarehouseId equals d.WarehouseId
                       group new { a, b, d, e, g } by a.MovelibraryCode into gs
                       select new MovelibraryMoveProductDTO
                       {
                           MovelibraryId = gs.First().a.MovelibraryId,
                           MovelibraryCode = gs.Key,
                           MovelibraryType = gs.First().a.MovelibraryType,
                           MorderNumber = gs.First().a.MorderNumber,
                           MakePerson = gs.First().a.MakePerson,
                           MarkTime = gs.First().a.MarkTime,
                           ORremark = gs.First().a.ORremark,
                           ReasonForReview = gs.First().a.ReasonForReview,
                           DocumentStatus = gs.First().a.DocumentStatus,
                           IsRemoved = gs.First().a.IsRemoved,
                           office_id = gs.First().a.office_id,
                           user_id = gs.First().a.user_id,

                           MoveProductId = gs.First().b.MoveProductId,
                           MoveProductNum = gs.First().b.MoveProductNum,
                           Movelocation = gs.First().b.Movelocation,

                           //StockId = gs.First().c.StockId,
                           //StockProductId = gs.First().c.StockProductId,
                           //ProductsID = gs.First().c.ProductsID,
                           //Batch = gs.First().c.Batch,
                           //Sprice = gs.First().c.Sprice,
                           //Quantity = gs.First().c.Quantity,
                           //Binlocation = gs.First().c.Binlocation,
                           //StateSP = gs.First().c.StateSP,
                           //ShenHePeople = gs.First().c.ShenHePeople,
                           //ShenHeTime = gs.First().c.ShenHeTime,

                           WarehouseCode = gs.First().d.WarehouseCode,
                           WarehouseName = gs.First().d.WarehouseName,
                           RentalTime = gs.First().d.RentalTime,
                           WarehouseType = gs.First().d.WarehouseType,
                           Department = gs.First().d.Department,
                           Waddress = gs.First().d.Waddress,
                           Area = gs.First().d.Area,
                           Wcontact = gs.First().d.Wcontact,
                           Wphone = gs.First().d.Wphone,
                           Function = gs.First().d.Function,

                           StorehouseCode = gs.First().e.StorehouseCode,
                           StorehouseName = gs.First().e.StorehouseName,
                           StorehouseType = gs.First().e.StorehouseType,
                           IsDisable = gs.First().e.IsDisable,
                           IsDefaults = gs.First().e.IsDefaults,
                           CreatTime = gs.First().e.CreatTime,
                           Sremark = gs.First().e.Sremark,

                           //StockCode = gs.First().f.StockCode,
                           //StockOrderType = gs.First().f.StockOrderType,
                           //SorderNumber = gs.First().f.SorderNumber,
                           //VendorId = gs.First().f.VendorId,
                           //VendorName = gs.First().f.VendorName,
                           //VendorContact = gs.First().f.VendorContact,
                           //VendorPhone = gs.First().f.VendorPhone,
                           //SRremark = gs.First().f.SRremark,

                           ProductsCode = gs.First().g.ProductsCode,
                           ProductsName = gs.First().g.ProductsName,
                           VendorsCode = gs.First().g.VendorsCode,
                           InteriorCode = gs.First().g.InteriorCode,
                           Specs = gs.First().g.Specs,
                           ProductTypeID = gs.First().g.ProductTypeID,
                           StorageUnits = gs.First().g.StorageUnits,
                           Upperlimit = gs.First().g.Upperlimit,
                           Lowerlimit = gs.First().g.Lowerlimit,
                           WrapType = gs.First().g.WrapType,
                           Price = gs.First().g.Price,
                           Weight = gs.First().g.Weight,
                           WarehouseId = gs.First().g.WarehouseId,
                           StorehouseId = gs.First().g.StorehouseId,
                           ClientId = gs.First().g.ClientId,
                           Describe = gs.First().g.Describe,
                           ProcurementNum = gs.First().g.ProcurementNum
                       };
            if (!string.IsNullOrEmpty(request.MovelibraryCode))
            {
                list = list.Where(t => t.MovelibraryCode == request.MovelibraryCode);
            }
            if (request.MovelibraryType > 0)
            {
                list = list.Where(t => t.MovelibraryType == request.MovelibraryType);
            }
            if (request.DocumentStatus > 0)
            {
                list = list.Where(t => t.DocumentStatus == request.DocumentStatus);
            }
            page.Totalcount = list.Count();//总条数
            page.Pagecount = (int)Math.Ceiling((request.PageIndex * 1.0) / request.PageSize);//总页数
            page.list = list.OrderBy(t => t.MovelibraryId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return page;
        }

        /// <summary>
        /// 产品
        /// </summary>
        /// <returns></returns>
        public async Task<dynamic> GetProductsList(int pindex, int psize)
        {
            string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyNiIsInNpZCI6IjE4NTk4MDM1MDY2MzA4NTY3MDQiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMiIsImp0aSI6IjQzMzA2NmRmLWYyNjAtNDI2Ny1iYWY5LWJkMzgxZGVhZGMwYiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiLku5jmtJvlmIkiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy91cmkiOiIiLCJpc3MiOiJSZW5hb2JvMjAwNCIsImF1ZCI6IldlaWZ1d3UyMjAzQSJ9.JtV8g_mbUcJgyPC793AMsvjLkmkeuiRR9BAH6rQp8aU";
            HttpClientWrapper cilent = new HttpClientWrapper(token);

            string chanpin = "http://116.205.121.197:8000/cpd/api/ProductRead/GetAllProductInfo?pageindex=" + pindex + "&pagesize=" + psize;

            string postReponse = await cilent.GetAsync(chanpin);
            var json = JsonConvert.DeserializeObject<ApiResultList<Products>>(postReponse);
            return json.data.list;
        }


        //产品
        public class Products
        {
            /// <summary>
            /// 产品id
            /// </summary>
            public int ProductsID { get; set; }
            /// <summary>
            /// 产品编号
            /// </summary>
            public string? ProductsCode { get; set; }
            /// <summary>
            /// 产品名称
            /// </summary>
            public string? ProductsName { get; set; }
            /// <summary>
            /// 厂商编码
            /// </summary>
            public string? VendorsCode { get; set; }
            /// <summary>
            /// 内部编码
            /// </summary>
            public string? InteriorCode { get; set; }
            /// <summary>
            /// 规格
            /// </summary>
            public string? Specs { get; set; }
            /// <summary>
            /// 产品类别
            /// </summary>
            public int? ProductTypeID { get; set; }
            /// <summary>
            /// 存储单位
            /// </summary>
            public string? StorageUnits { get; set; }
            /// <summary>
            /// 预警（上）
            /// </summary>
            public int? Upperlimit { get; set; }
            /// <summary>
            /// 预警（下）
            /// </summary>
            public int? Lowerlimit { get; set; }
            /// <summary>
            /// 包装类型
            /// </summary>
            public int? WrapType { get; set; }
            /// <summary>
            /// 价格
            /// </summary>
            public decimal? Price { get; set; }
            /// <summary>
            /// 重量
            /// </summary>
            public decimal? Weight { get; set; }
            /// <summary>
            /// 默认仓库
            /// </summary>
            public int? WarehouseId { get; set; }
            /// <summary>
            /// 库位
            /// </summary>
            public int? StorehouseId { get; set; }
            /// <summary>
            /// 默认供应商
            /// </summary>
            public int? VendorId { get; set; }
            /// <summary>
            /// 默认客户
            /// </summary>
            public int? ClientId { get; set; }
            /// <summary>
            /// 描述
            /// </summary>
            public string? Describe { get; set; }
            /// <summary>
            /// 产品数量
            /// </summary>
            public int? ProcurementNum { get; set; }
            /// <summary>
            /// 公司id
            /// </summary>
            public string? Office_Id { get; set; }

            /// <summary>
            /// 用户id
            /// </summary>
            public int? User_Id { get; set; }
        }
    }
}
